﻿(function(){
	function Linkage(config){
		this.init(config);
	}
	
	Linkage.prototype = {
			data:[],
			nodes:[],
			init:function(config){
				this.nodes = config.nodes;
				this.data = config.data;
				this.labelAsKey = config.labelAsKey;
				this.onChange = config.onChange || function(){};
				this.bindEvent();
			},
			bindEvent:function(){
				var _this = this;
				var len = _this.nodes.length;
				for(var i=0; i<len; i++){
					var node = _this.nodes[i]; 
					if(i+1< len){
						node.data("child", this.nodes[i+1]);
						node.bind("change", function(){
							var items = $(this).data("items");
							var child = $(this).data("child");
							var children = [];
							for(var j=0;j<items.length; j++){
								var item = items[j];
								var value = _this.labelAsKey ? item.label : item.id;
								if(value == this.value){
									children = item.children;
									break;
								}
							}
							child.data("items", children);
							_this.buildHtml(child, children);
						
							_this.onChange();
						});
					}
					else{
						node.bind("change", function(){							
							_this.onChange();
						});
					}
					if(i==0){
						node.data("items", this.data);
						this.buildHtml(node, this.data, true);
					}
					else{
						this.buildHtml(node, [], true);
					}
				}
				
				_this.nodes[0].trigger("change");
			},
			buildHtml:function(node, data, isInit){
				var selectedValue = node.val() || node.data("value");
				var label = node.data("label") ||"";
				var arr = ['<option value="">--请选择' + label + '--</option>'];
				for(var i=0; i<data.length;i++){
					var item = data[i];
					var value = this.labelAsKey ? item.label : item.id;
					var selected = selectedValue == value ? 'selected="selected"':'';
					arr.push('<option value="'+ value +'" '+ selected +'>'+ htmlEncode(item.label) +'</option>');
				}
				node.html(arr.join("\n"));
				if(selectedValue){
					node.data("value", selectedValue);
					if(!isInit){						
						node.trigger("change");
					}
				}
			}
	}
	
	window.Linkage = Linkage;

})();